import axios from "axios";
import {clearToken, confirmMessageTip, messageTip} from "@/util/utils";


//请求上下文
axios.defaults.baseURL = "http://192.168.110.22:8089"
export function doGet(url,param){
    return axios.get(url,{
        params: param
    })

}

//axios请求拦截器传递token
axios.interceptors.request.use((config) =>{
    let token = window.sessionStorage.getItem("token");
    if (!token) {
        token = window.localStorage.getItem("token");
        if (token){
            config.headers['rememberMe'] = true;
        }
    }
    if (token) {
        //放入请求头
        config.headers['Authorization'] = token;
    }else {
        if (config.url != "/" && config.url !== "/login"){
            window.location.href = "/"
            return config;
        }
    }

    return config;
}, (error) =>{
    //请求错误时的处理
    return Promise.reject(error);
})

//axios响应拦截器
axios.interceptors.response.use((res) =>{
    if (res.data.code >= 900){
        confirmMessageTip(res.data.msg + ", 是否重新登录？").then(() =>{
            //清除token
            clearToken();
            window.location.href = "/"
        }).catch(()=>{
            messageTip("取消", "info")
        })
    }
    return res;
})

export function doDelete(url,param){
    return axios.delete(url,{
        params: param
    })
}
export function doPost(url, data){
    return axios.post(url, data)
}
export function doPut(url, data){
    return axios.put(url, data)
}

